package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录检查过滤器
 *
 * @author panda
 * @since 2022/12/28 1:00
 */
@Slf4j
@WebFilter(filterName = "loginFilter")
public class LoginCheckFilter implements Filter {
    final AntPathMatcher pathMatcher = new AntPathMatcher();

    private String[] authUrl = new String[]{
            "/favicon.ico",
            "/employee/login*",
            "/employee/logout",
            "/backend/**",
            "/front/**",
            "/user/sendMsg",
            "/user/login",
            "/doc.html",
            "/webjars/**",
            "/swagger-resources",
            "/v2/api-docs"
    };

    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        //先进行转换请求和响应http
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1、获取本次请求的URI
        String requestURI = request.getRequestURI();
        //进行判断是否符合放行要求
        if (CheckAuthUrl(requestURI)) {
            //如果符合就放行
            filterChain.doFilter(request,response);
            return;
        }


        //如果不符合,判断登录状态,是否登录
        //后端员工登录
        Long empId = (Long)request.getSession().getAttribute("employee");
        if (empId != null) {
            /**
             * 在过滤器中将session中的ID放入到ThreadLocal当中
             * 待以后的同线程阶段调用
             */
            BaseContext.setCurrentId(empId);
            filterChain.doFilter(request, response);
            return;
        }
        //移动端登陆判断
        Long userId = (Long)request.getSession().getAttribute("user");
        if (userId != null) {
            /**
             * 在过滤器中将session中的ID放入到ThreadLocal当中
             * 待以后的同线程阶段调用
             */
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request, response);
            return;
        }


        //如果即不再放行内容中也没有登录信息则拦截不放行
        log.info("登录失败");
        //注意返回的信息，必须是NOTLOGIN，否则客户端无法跳转，因为前端检查是是字符串是否是NOTLOGIN
        R<Object> notlogin = R.error("NOTLOGIN");
        String  notLoginJsonString= JSON.toJSONString(notlogin);
        response.getWriter().write(notLoginJsonString);

    }

    private boolean CheckAuthUrl(String uri) {

        for (String url : authUrl) {
            if(pathMatcher.match(url,uri)){
                return true;
            }
        }
        return false;
    }
}